package start

import (
	"gitee.com/go-course/go11/vblog/apps/blog/api"
	"gitee.com/go-course/go11/vblog/apps/blog/impl"
	"gitee.com/go-course/go11/vblog/conf"
	"gitee.com/go-course/go11/vblog/protocol"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var (
	configType string
	configFile string
)

// root command
// vblog-api start
var Cmd = &cobra.Command{
	Use:   "start",
	Short: "vblog项目后端",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		// 命令具体的执行逻辑
		// vblog-api start xxx xxx xxx
		// [xxx xxx xxx]

		// 程序的组装

		// 1. 加载全局配置
		switch configType {
		case "env":
			_, err := conf.LoadConfigFromEnv()
			cobra.CheckErr(err)
		default:
			// 默认通过配置文件加载
			_, err := conf.LoadConfigFromToml(configFile)
			cobra.CheckErr(err)
		}

		// 加载业务逻辑实现
		r := gin.Default()

		// blog 业务模块
		blogService := &impl.Impl{}
		err := blogService.Init()
		cobra.CheckErr(err)
		apiHandler := api.NewHandler(blogService)
		apiHandler.Registry(r)

		// 启动协议服务器
		httpServer := protocol.NewHttp(r)
		err = httpServer.Start()
		cobra.CheckErr(err)
	},
}

func init() {
	// Flag --config-type -t file -f etc/config.toml
	Cmd.Flags().StringVarP(&configType, "config-type", "t", "file", "程序加载配置的方式")
	Cmd.Flags().StringVarP(&configFile, "config-file", "f", "etc/config.toml", "配置文件的路径")
}
